package com.yingxin.yxerp.module.activiti.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yingxin.yx.framework.commons.activiti.ApprovalStatus;
import com.yingxin.yxerp.module.activiti.entity.ActivitiBizInfo;
import com.yingxin.yxerp.module.activiti.mapper.ActivitiBizInfoMapper;
import com.yingxin.yxerp.module.activiti.service.IActivitiBizInfoService;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

/**
 * activiti biz 服务实现类
 * @author fanchao
 * @since 2022-02-19
 */

@Service
public class ActivitiBizInfoServiceImpl extends ServiceImpl<ActivitiBizInfoMapper, ActivitiBizInfo> implements IActivitiBizInfoService {

    @Override
    public List<ActivitiBizInfo> listByBizIds(Collection<String> bizIds) {
        if (CollectionUtil.isEmpty(bizIds)) {
            return new ArrayList<>();
        }
        QueryWrapper<ActivitiBizInfo> qw = new QueryWrapper<>();
        qw.lambda().in(ActivitiBizInfo::getBizId, bizIds);
        return list(qw);
    }

    @Override
    public List<ActivitiBizInfo> listByProcessInstanceIds(Collection<String> processInstanceIds) {
        if (CollectionUtil.isEmpty(processInstanceIds)) {
            return new ArrayList<>();
        }
        QueryWrapper<ActivitiBizInfo> qw = new QueryWrapper<>();
        qw.lambda().in(ActivitiBizInfo::getProcessInstanceId, processInstanceIds);
        return list(qw);
    }

    @Override
    public ActivitiBizInfo getByProcessInstanceId(String processInstanceId) {
        QueryWrapper<ActivitiBizInfo> qw = new QueryWrapper<>();
        qw.lambda().eq(ActivitiBizInfo::getProcessInstanceId, processInstanceId);
        return getOne(qw);
    }


    @Override
    public void updateApprovalStatus(String bizId, ApprovalStatus approvalStatus, String assignee, String currentAssignee) {
        UpdateWrapper<ActivitiBizInfo> uw = new UpdateWrapper<>();
        uw.lambda().set(ActivitiBizInfo::getApprovalStatus, approvalStatus.getStatus());
        uw.lambda().set(ActivitiBizInfo::getCurrentAssigneeInfo, currentAssignee);
        uw.lambda().set(ActivitiBizInfo::getLastAssigneeInfo, assignee);
        uw.lambda().eq(ActivitiBizInfo::getBizId, bizId);
        update(new ActivitiBizInfo(), uw);
        // 第一位审核人
        uw = new UpdateWrapper<>();
        uw.lambda().set(ActivitiBizInfo::getFirstAssigneeInfo, assignee);
        uw.lambda().eq(ActivitiBizInfo::getBizId, bizId);
        uw.lambda().isNull(ActivitiBizInfo::getFirstAssigneeInfo);
        update(new ActivitiBizInfo(), uw);
    }
}